/*
 *  Copyright 2010 dmakariev.
 * 
 */
package org.deltaset.faces.upload;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import org.deltaset.faces.FacesUtils;

/**
 *
 * @author dmakariev
 */
public class StreamPhaseListener implements PhaseListener {

    private static final long serialVersionUID = -8260022229570469693L;
    private static final Logger logger = Logger.getLogger(StreamPhaseListener.class.getName());
    private static final String DELTASET_STREAMER = "deltasetStreamer";

    @Override
    public void afterPhase(PhaseEvent pe) {
        // do nothing
    }

    @Override
    public void beforePhase(PhaseEvent pe) {
        if (false == isDeltasetStreamer()) {
            return;
        }
        final CurrentFile currentFile = loadCurrentFile();//loadObject(CurrentFile.class);
        StreamCurrentFile.streamCurrentFile(currentFile);
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }

    private static CurrentFile loadCurrentFile() {
        final String fileLookupExpression = Base64Util.decode(FacesUtils.getParameterString(DELTASET_STREAMER));
        logger.log(Level.INFO, " fileLookupExpression={0}", fileLookupExpression);
        final FileSessionCache cache = new FileSessionCache();
        final CurrentFile currentFile = cache.resolveFile(fileLookupExpression);
        logger.log(Level.INFO, "currentFile={0}", currentFile);
        //return FacesUtils.getManagedBean(fileLookupExpression, clazz);
        return currentFile;
    }

    private static boolean isDeltasetStreamer() {
        return null != FacesUtils.getParameterString(DELTASET_STREAMER);
    }

    public static String prepareUrl(final CurrentFile currentFile) {
        final FileSessionCache cache = new FileSessionCache();
        final String fileKey = cache.fileSessionKey(currentFile);
        final ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
        final String encodedAccessUrl = ctx.getRequestContextPath() + ctx.getRequestServletPath() + "?" + DELTASET_STREAMER + "=" + Base64Util.encode(fileKey) + "&t=" + new Date().getTime();
        return encodedAccessUrl;
    }
}
